/*
 * Project Name spring-boot-tools
 * File Name Action101
 * Package Name com.huxiaosu.tools.mina.action
 * Create Time 2024/5/25
 * Create by name：liujie
 */
package com.huxiaosu.tools.mina.action;

import com.alibaba.fastjson2.JSONObject;
import com.huxiaosu.tools.mina.cache.SessionUsers;
import com.huxiaosu.tools.mina.model.BaseMessage;
import com.huxiaosu.tools.mina.utils.Constants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * Description
 *
 * @author liujie
 * @date 2024/5/25 14:45
 */
@Slf4j
@Component
public class Action103 extends AbstractMessageAction {
    @Override
    public byte getMessageCommandId() {
        return Constants.T103;
    }

    @Override
    public String getMessageCommandName() {
        return "PushTest";
    }

    @Override
    @SneakyThrows(value = Throwable.class)
    public void execute() {
        log.info("<给用户推送消息 = {}>",message.getBody());
        String orderInfo = new String(message.getBody());
        JSONObject orderJson = JSONObject.parseObject(orderInfo);
        String userId = orderJson.getString("userId");
        // 提取
        Set<String> sessionIds = (Set<String>) cacheService.get(userId);
        sessionIds.forEach(item-> {
            IoSession userSession = (IoSession) SessionUsers.getInstance().getSession(item);
            if(userSession == null){
                log.info("<用户[{}]已关闭次连接[{}]>",userId,item);
                SessionUsers.getInstance().clearSession(item);
                return;
            }
            boolean sessionStatus = userSession.isConnected();
            if(!sessionStatus){
                log.info("<用户[{}]已关闭次连接[{}]>",userId,item);
                SessionUsers.getInstance().clearSession(item);
                return;
            }
            userSession.write(message.toByte());
            log.info("<push  message success to [{}=>>{}]>",userId,item);

        });
        // 告诉调用人
        JSONObject json = new JSONObject();
        json.put("status", Constants.SUCCESS);
        json.put("result", "push message success to user");
        BaseMessage responseMessage = new BaseMessage();
        responseMessage.setType(Constants.T103);
        responseMessage.setBody(json.toString().getBytes(Constants.CHARSET));
        responseMessage.setBodyLength(json.toString().getBytes(Constants.CHARSET).length);
        session.write(responseMessage.toByte());
    }
}
